package com.genghis.rapidcrm.kernel.module;

import com.genghis.rapidcrm.kernel.RapidLinkModel;
import com.genghis.rapidcrm.kernel.RapidLinkModelProvider;
import com.genghis.rapidcrm.kernel.UsersPrivilegesModel;
import com.genghis.rapidcrm.kernel.service.RapidWorkflowService;
import com.genghis.rapidcrm.module.SettingsWebformsModuleModelManager;
import edu.jetwinner.common.EasyStringUtil;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xulixin
 */
@Component(RapidModuleModel.DEFAULT_MODULE_BEAN_NAME)
public class RapidModuleModel extends RapidModule {

    public static final String DEFAULT_MODULE_BEAN_NAME = "rapidModuleModel";

    protected final RapidLinkModelProvider linkModelProvider;
    protected final RapidWorkflowService workflowService;
    protected final SettingsWebformsModuleModelManager settingsWebformsModuleModelManager;

    public RapidModuleModel(RapidLinkModelProvider linkModelProvider,
                            RapidWorkflowService workflowService,
                            SettingsWebformsModuleModelManager settingsWebformsModuleModelManager) {

        this.linkModelProvider = linkModelProvider;
        this.workflowService = workflowService;
        this.settingsWebformsModuleModelManager = settingsWebformsModuleModelManager;
    }

    @Override
    public String getName() {
        return "Rapid";
    }


    /**
     * Function to get the ListView Component Name
     *
     * @return string
     */
    public String getListViewName() {
        return "List";
    }

    /**
     * Function to get the url for the Create Record view of the module
     *
     * @return <String> - url
     */
    public String getCreateRecordUrl() {
        return "/" + this.getName() + "/Create";
    }

    public String getImportUrl() {
        return "/" + this.getName() + "/Import";
    }

    public String getExportUrl() {
        return "/" + this.getName() + "/Export";
    }

    /**
     * Function to check whether the module is an entity type module or not
     *
     * @return <Boolean> true/false
     */
    public Boolean isEntityModule() {
        return "1".equals(this.isEntityType);
    }

    /**
     * Function to identify if the module supports quick search or not
     */
    public Boolean isQuickSearchEnabled() {
        return Boolean.TRUE;
    }

    /**
     * Function to get the url for list view of the module
     *
     * @return <string> - url
     */
    public String getListViewUrl() {
        return this.getName() + "/view/" + this.getListViewName();
    }

    /**
     * Function checks if a module has module sequence numbering
     *
     * @return boolean
     */
    public boolean hasSequenceNumberField() {
        return false;
    }

    /**
     * Function to get the Quick Links for the module
     *
     * @param linkParams <Array>
     * @return <Array> List of Vtiger_Link_Model instances
     */
    public Map<String, List<RapidLinkModel>> getSideBarLinks(Map<String, Object> linkParams) {
        String[] linkTypes = {"SIDEBARLINK", "SIDEBARWIDGET"};
        Map<String, List<RapidLinkModel>> links = linkModelProvider.getAllByType(this.getId(), linkTypes, linkParams);

        List<RapidLinkModel> quickLinks = new ArrayList<>();
        RapidLinkModel linkModel = new RapidLinkModel().setLinkType("SIDEBARLINK")
                .setLinkLabel("LBL_RECORDS_LIST").setLinkUrl(this.getListViewUrl()).setLinkIcon("");
        quickLinks.add(linkModel);

        links.put("SIDEBARLINK", quickLinks);

        List<RapidLinkModel> quickWidgets = new ArrayList<>();
        linkModel.setLinkType("SIDEBARWIDGET").setLinkLabel("LBL_RECENTLY_MODIFIED")
                .setLinkUrl(this.getName() + "/showActiveRecords").setLinkIcon("");
        quickWidgets.add(linkModel);

        links.put("SIDEBARWIDGET", quickWidgets);

        return links;
    }

    /**
     * Function to get the list of all searchable modules
     *
     * @return <Array> - List of Rapid_Module_Model instances
     */
    public Map<String, RapidModuleModel> getSearchableModules() {
        UsersPrivilegesModel usersPrivilegesModel = UsersPrivilegesModel.getCurrentUserPrivilegesModel();

        List<RapidModuleModel> entityModules = this.getEntityModules();

        Map<String, RapidModuleModel> searchableModules = new HashMap<>(entityModules.size());
        for (RapidModuleModel moduleModel : entityModules) {
            String moduleName = moduleModel.getName();
            if (EasyStringUtil.inArray(moduleName, "Users", "Emails", "Events", "Rapid")) {
                continue;
            }
            if (usersPrivilegesModel.hasModuleActionPermission(moduleModel.getId(), "DetailView")) {
                searchableModules.put(moduleName, moduleModel);
            }
        }
        return searchableModules;
    }

    private List<RapidModuleModel> getEntityModules() {
        try {
            return new ArrayList<>(this.applicationContext.getBeansOfType(RapidModuleModel.class).values());
        } catch (Exception e) {
            return new ArrayList<>(0);
        }
    }

    /**
     * Function to get Settings links
     *
     * @return <Array>
     */
    public List<RapidLinkModel> getSettingLinks() {
        if (!this.isEntityModule()) {
            return new ArrayList<>(0);
        }

        List<RapidLinkModel> settingsLinks = new ArrayList<>();

        settingsLinks.add(new RapidLinkModel()
                .setLinkType("LISTVIEWSETTING")
                .setLinkLabel("LBL_EDIT_FIELDS")
                .setLinkUrl("/Settings/LayoutEditor?sourceModule=" + this.getName())
                .setLinkIcon("LayoutEditor.gif"));

        if (workflowService.checkModuleWorkflow(this.getName())) {
            settingsLinks.add(new RapidLinkModel()
                    .setLinkType("LISTVIEWSETTING")
                    .setLinkLabel("LBL_EDIT_WORKFLOWS")
                    .setLinkUrl("/Settings/Workflows?view=List&sourceModule=" + this.getName())
                    .setLinkIcon("EditWorkflows.png"));
        }

        settingsLinks.add(new RapidLinkModel()
                .setLinkType("LISTVIEWSETTING")
                .setLinkLabel("LBL_EDIT_PICKLIST_VALUES")
                .setLinkUrl("/Settings/Picklist?view=Index&source_module=" + this.getName())
                .setLinkIcon(""));

        if (this.hasSequenceNumberField()) {
            settingsLinks.add(new RapidLinkModel()
                    .setLinkType("LISTVIEWSETTING")
                    .setLinkLabel("LBL_MODULE_SEQUENCE_NUMBERING")
                    .setLinkUrl("/Settings/Vtiger?view=CustomRecordNumbering&sourceModule=" + this.getName())
                    .setLinkIcon(""));
        }

        Map<String, String> webformSupportedModule = settingsWebformsModuleModelManager.getSupportedModulesList();
        if (webformSupportedModule.containsKey(this.getName())) {
            settingsLinks.add(new RapidLinkModel()
                    .setLinkType("LISTVIEWSETTING")
                    .setLinkLabel("LBL_SETUP_WEBFORMS")
                    .setLinkUrl("/Settings/Webforms?view=Edit&sourceModule=" + this.getName())
                    .setLinkIcon(""));
        }
        return settingsLinks;
    }

    public Boolean isPermitted(String actionName) {
        return true;
    }

    public boolean isCommentEnabled() {
        return true;
    }
}
